package com.jxnu.escms.utils;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Lenovo
 * 更新全国疫情数据
 * 使用者只要调佣updateData方法就可以自动调用爬虫脚本更新疫情数据。
 */
@Data
@Component
@ConfigurationProperties(prefix = "epidemic")
public class UpdateData {
    private String python;
    private String spider;

    public void updateData(){
        ProcessBuilder pd = new ProcessBuilder(python, spider);
        pd.redirectErrorStream(true);
        Process p = null;
        try{
            p = pd.start();
            new Thread(new ProcessTestRunnable(p)).start();
            p.waitFor();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

class ProcessTestRunnable implements Runnable{
    Process p;
    BufferedReader br;
    ProcessTestRunnable(Process p){
        this.p = p;
    }

    @Override
    public void run() {
        try{
            InputStreamReader isr = new InputStreamReader(p.getInputStream(),"GBK");
            br = new BufferedReader(isr);
            String line = null;
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }

    }
}